<?php
/**
 * 数据库操作类
 */

class Database {
    private $connection;

    public function __construct() {
        try {
            $dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4";
            $this->connection = new PDO($dsn, DB_USER, DB_PASS, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
            ]);
        } catch (PDOException $e) {
            throw new Exception("数据库连接失败: " . $e->getMessage());
        }
    }

    public function getConnection() {
        return $this->connection;
    }

    public function query($sql, $params = []) {
        try {
            $stmt = $this->connection->prepare($sql);
            $stmt->execute($params);
            return $stmt;
        } catch (PDOException $e) {
            throw new Exception("数据库操作失败: " . $e->getMessage());
        }
    }

    public function fetchAll($sql, $params = []) {
        return $this->query($sql, $params)->fetchAll();
    }

    public function fetchOne($sql, $params = []) {
        return $this->query($sql, $params)->fetch();
    }

    public function createTables() {
        $sql = "
            CREATE TABLE IF NOT EXISTS files (
                id INT AUTO_INCREMENT PRIMARY KEY,
                original_name VARCHAR(255) NOT NULL,
                stored_name VARCHAR(255) NOT NULL,
                file_path VARCHAR(500) NOT NULL,
                file_size BIGINT NOT NULL,
                file_type VARCHAR(100),
                file_ext VARCHAR(10),
                upload_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                download_count INT DEFAULT 0,
                delete_code VARCHAR(32),
                direct_link VARCHAR(64) UNIQUE,
                INDEX idx_upload_time (upload_time)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        ";

        $this->query($sql);
    }

    /**
     * 管理员登录验证
     */
    public function verifyAdmin($username, $password) {
        $admin = $this->fetchOne("SELECT * FROM admins WHERE username = ?", [$username]);
        if ($admin && password_verify($password, $admin['password'])) {
            return true;
        }
        return false;
    }

    /**
     * 生成唯一直链
     */
    public function generateDirectLink($fileId) {
        // 生成随机字符串作为直链
        $link = bin2hex(random_bytes(16));

        // 确保直链唯一
        $attempts = 0;
        while ($attempts < 10) {
            try {
                // 先检查该link是否已存在
                $exists = $this->fetchOne("SELECT id FROM files WHERE direct_link = ?", [$link]);
                if (!$exists) {
                    $this->query("UPDATE files SET direct_link = ? WHERE id = ?", [$link, $fileId]);
                    return $link;
                }
            } catch (Exception $e) {
                // 继续尝试
            }
            // 重新生成
            $link = bin2hex(random_bytes(16));
            $attempts++;
        }

        // 如果还是失败，使用更长的字符串
        $link = uniqid() . bin2hex(random_bytes(8));
        $this->query("UPDATE files SET direct_link = ? WHERE id = ?", [$link, $fileId]);
        return $link;
    }

    /**
     * 获取直链
     */
    public function getDirectLink($fileId) {
        $file = $this->fetchOne("SELECT direct_link FROM files WHERE id = ?", [$fileId]);
        return $file ? $file['direct_link'] : null;
    }

    /**
     * 获取文件的详情信息
     */
    public function getFileDetails($fileId) {
        return $this->fetchOne("SELECT * FROM files WHERE id = ?", [$fileId]);
    }

    /**
     * 保存或更新文件详情
     */
    public function saveFileDetails($fileId, $data) {
        $sql = "UPDATE files SET
                    file_title = ?,
                    file_description = ?,
                    page_title = ?,
                    page_description = ?
                WHERE id = ?";
        $params = [
            $data['file_title'] ?? null,
            $data['file_description'] ?? null,
            $data['page_title'] ?? null,
            $data['page_description'] ?? null,
            $fileId
        ];
        $this->query($sql, $params);
        return true;
    }

    /**
     * 获取所有文件列表（用于选择）
     */
    public function getAllFiles() {
        return $this->fetchAll("SELECT * FROM files ORDER BY upload_time DESC");
    }
}
